package testshop.tools;


import testshop.db.DbClose;
import testshop.db.DbConn;
import testshop.entity.Goods;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public final class QueryPrint
{

    Connection  conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;


      /**
           * 方法实现说明
           * @method
           * @author      周灿
           * @version
           * @param
           * @return   查询到的信息的gid,如果返回值等于-1，则代表查询异常
           * @exception
           * @date        2018/3/16 10:56
           */

    public static  int query(String oper)
    {
        int gid = -1;

        String shopping = ScannerChoice.ScannerInfoString(); //获取要更改的商品名字

        ArrayList<Goods> goodsList = new QueryPrint().queryGoodsKey(gid,shopping);

        if (goodsList == null || goodsList.size() <= 0 ){


            System.out.println("\t查无此商品！！！");
           ScannerChoice.changeInfoNext(oper);


        }else{

            Goods goods = goodsList.get(0);

            System.out.println("\t\t\t\t\t商品列表\n\n");
            System.out.println("\t商品编号\t\t商品名称\t\t商品价格\t\t商品数量\t\t备注\n");
            System.out.print("\t"+goods.getGid()+"\t\t"+goods.getGname()+"\t\t"+goods.getGprice()+"\t\t"+goods.getGnum());
            if (goods.getGnum()==0)
            {
                System.out.println("\t\t该商品已售空");
            }else if (goods.getGnum()<10)
            {
                System.out.println("\t\t该商品已不足10件");
            }else
            {
                System.out.println("\t\t-");
            }
            gid = goods.getGid(); //将商品编号返回给调用者

        }

        return gid;



    }



    public  ArrayList<Goods> queryGoodsKey(int gId,String gName){

        ArrayList<Goods> goodsList = new ArrayList<Goods>();

        conn = DbConn.getconn();

        String sql = " SELECT * FROM goods WHERE gid = ? OR gname = ?";

        try{

            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,gId);
            pstmt.setString(2,gName);
            rs = pstmt.executeQuery();
            while (rs.next()){

                int gid = rs.getInt("gid");
                String gname = rs.getString("gname");
                double gprice =  rs.getDouble("gprice");
                int gnum = rs.getInt("gnum");

                Goods goods = new Goods(gid,gname,gprice,gnum);

                goodsList.add(goods);


            }


        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DbClose.queryClose(pstmt,rs,conn);
        }
        return  goodsList;

    }































}
